package com.dongbao.listeners;

import com.dongbao.common.MessageConstant;
import com.dongbao.data.Datacenter;
import com.dongbao.entity.FileLog;
import com.dongbao.entity.MqMessage;
import com.dongbao.service.MyMqttClient;
import com.dongbao.util.IdeaApiUtil;
import com.dongbao.util.InitUtil;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

public class TabFileSwitchListeners implements FileEditorManagerListener {

    private Project project;

    private ChangeListManagerImpl myChangeListManager;

    private LocalChangeList localChangeList;

    public TabFileSwitchListeners(Project project){
        System.out.println("TabFileSwitchListeners");
        MessageBusConnection connection = project.getMessageBus().connect(project);
        connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() {
            @Override
            public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
                fileOpenedEx(source,file);
            }
        });
        connection.subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener() {
            @Override
            public void enteredDumbMode() {
                System.out.println("enteredDumbMode");
            }

            @Override
            public void exitDumbMode() {
                System.out.println("exitDumbMode");
            }
        });
    }

    /**
     * 文件打开事件监听
     * @auto: WangZhiKun
     * @Date: 2021年9月23日11:41:13
     * */
    public void fileOpenedEx( FileEditorManager source,  VirtualFile file) {
        System.out.println("fileOpened");
        /* 检测是否是在核心文件列表中 */
        if(Datacenter.protectFiles.size()==0){
            InitUtil.initFileList();
        }
        if(Datacenter.project == null){
            Datacenter.project = source.getProject();
        }

        if(Datacenter.protectFiles.size()>0){
            List<FileLog> isAuthorityFile = Datacenter.protectFiles.stream().filter(log -> log.getFileName().equals(file.getName())).collect(Collectors.toList());
            if(isAuthorityFile.size()>0){
                /* 如果变更集合管理服务为null则初始化 */
                if (myChangeListManager == null){
                    myChangeListManager = (ChangeListManagerImpl)ChangeListManager.getInstance(source.getProject());
                }

                /* 判断当前是否存在核心类的分类 */
                LocalChangeList changeList = myChangeListManager.getChangeList("核心类,不允许提交");
                if(changeList == null){
                    /* 如果没有则创建 */
                    localChangeList = addChangeList("核心类,不允许提交","DHG核心类文件,不允许提交,请取消勾选！");
                }

                /* 将当前打开的类文件添加到核心类的集合中 */
                Change change = new Change(null,new CurrentContentRevision(VcsUtil.getFilePath(file)));
                myChangeListManager.moveChangesTo(localChangeList, change);
                FileLog log = isAuthorityFile.get(0);
                /* TODO:判断当前主机IP是否在白名单中 (本地测试时注释)*/
//                if(log.getLeaderIp().indexOf(Datacenter.clientIp)>-1){
//                    /* 当前类的白名单中存在此主机,所以跳过提示验证操作 */
//                    return;
//                }
                /* 复制更新脚本失败 */
                IdeaApiUtil.showNotification(String.format("当前编辑的类为核心业务类,进行修改请联系负责人【%s】,文件描述:%s,核心逻辑：%s;",log.getLeader(),log.getDesc(),log.getLogic()),log.getNotificationType(),project);

                ExecutorService executor = Executors.newSingleThreadExecutor();
                Future<Integer> future = executor.submit(new Callable<Integer>() {
                    @Override
                    public Integer call() throws Exception {
                        /* 发送MQ消息给负责人 */
                        String leaderIp = log.getLeaderIp();
                        if(null!=leaderIp && !"".equals(leaderIp)){
                            String[] ips = leaderIp.split(",");
                            for(String ip:ips){
                                MqMessage message = MqMessage.getInstance();
                                message.setCode(MessageConstant.ASSIGN_IP_MESSAGE);
                                message.setMessage(String.format("有人在修改您负责的核心业务类,修改者IP[%s],请注意。",Datacenter.clientIp));
                                Datacenter.myMqttClient.publishMessage(MyMqttClient.TOPIC_PREFIX+ip,message,1);
                            }
                        }
                        return 3;
                    }
                });

            }
        }
    }

    public void fileClosedEx( FileEditorManager source,  VirtualFile file) {
        System.out.println("fileClosed");

    }

    public void selectionChangedEx( FileEditorManagerEvent event) {
        System.out.println("selectionChanged");

    }

    public void beforeFileOpenedEx( FileEditorManager source,  VirtualFile file) {
        System.out.println("beforeFileOpened");

    }

    public void beforeFileClosedEx( FileEditorManager source,  VirtualFile file) {
        System.out.println("beforeFileClosed");

    }

    private LocalChangeList addChangeList(String title,String comment) {
        final LocalChangeList list = myChangeListManager.addChangeList(title, comment);
        return list;
    }




}
